from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from faq.models import Question, PendingQuestion

class QuestionForm(forms.Form):
	name = forms.CharField(min_length = 2, help_text = _('What is your name?'))
	email = forms.EmailField(help_text = _('Your email is required to verify you are a person.  We will not share your email with anyone.'))
	question = forms.CharField(help_text = _('What is your question?'))
	
	def clean_question(self):
		q = self.cleaned_data.get('question')
		all_matching = Question.objects.filter(slug = slugify(q))
		published_matching = Question.objects.published(slug = slugify(q))
		if published_matching.count() != 0:
			raise forms.ValidationError(_('This question has already been answered.'))
		if all_matching.count() != 0:
			raise forms.ValidationError(_('This question has already been asked.'))
		return q
	
	def save(self):
		new_q = Question(
			question = self.cleaned_data.get('question'),
			slug = slugify('%s' % self.cleaned_data.get('question')),
			published = False
		)
		new_q.save()
		
		new_pending = PendingQuestion(
			name = self.cleaned_data.get('name'),
			email = self.cleaned_data.get('email'),
			question = new_q,
			activation_code = User.objects.make_random_password(48)
		)
		new_pending.save()
		
		return new_pending
